package com.cjy.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import com.cjy.dao.BlogRepository;
import com.cjy.dao.ThumbUpRepository;
import com.cjy.pojo.Blog;
import com.cjy.pojo.SystemResult;
import com.cjy.pojo.ThumbUp;
import com.cjy.pojo.User;
import com.cjy.service.BlogService;
import com.cjy.service.ThumbUpService;
import com.cjy.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Service
public class ThumbUpServiceImpl implements ThumbUpService {

    @Autowired
    private ThumbUpRepository thumbUpRepository;

    @Autowired
    private HttpSession session;

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagServiceImpl tagService;

    @Override
    public List<ThumbUp> getThumbUpByUid(Long uid) {
        return thumbUpRepository.findByUserId(uid);
    }

    @Override
    @Transactional
    public ThumbUp updateThumbup(Long blogId) {
        User user = (User) session.getAttribute("user");
        if (ObjectUtil.isNull(user)){
            return null;
        }
        ThumbUp thumbUp = thumbUpRepository.findByUserIdAndBlogId(user.getId(), blogId);
        thumbUp = thumbUp == null ? new ThumbUp() : thumbUp;
        thumbUp.setId(thumbUp == null ? null : thumbUp.getId());
        thumbUp.setCancel(thumbUp.getCancel() == null ? false : !thumbUp.getCancel());
        thumbUp.setUserId(user.getId());
        thumbUp.setBlogId(blogId);
        ThumbUp save = thumbUpRepository.save(thumbUp);

        if (ObjectUtil.isNotNull(save)) {
            if (save.getCancel()) {
                blogService.updateBlogReduceLike(blogId,null);
            }else {
                blogService.updateBlogAddLike(blogId,null);
            }
            return save;
        }
        return null;
    }
}
